package com.company.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.project.common.utils.DataResult;
import com.company.project.entity.MobileRecordEntity;
import com.company.project.service.MobileRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.company.project.common.utils.DateUtils;
import com.company.project.common.utils.ParamUtils;

/**
 * 移动备案记录Controller
 */
@Api(tags = "移动备案记录管理")
@RestController
@RequestMapping("/mobileRecord")
@Slf4j
public class MobileRecordController {

    @Autowired
    private MobileRecordService mobileRecordService;

    @ApiOperation(value = "新增移动备案记录")
    @PostMapping("/add")
    public DataResult add(@RequestBody MobileRecordEntity entity) {
        try {
            entity.setCreateTime(new Date());
            entity.setUpdateTime(new Date());
            entity.setStatus(0); // 默认待提交状态
            mobileRecordService.save(entity);
            return DataResult.success();
        } catch (Exception e) {
            log.error("新增移动备案记录异常：" + e.getMessage());
            return DataResult.fail("新增失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "删除移动备案记录")
    @DeleteMapping("/delete/{id}")
    public DataResult delete(@PathVariable Integer id) {
        try {
            mobileRecordService.removeById(id);
            return DataResult.success();
        } catch (Exception e) {
            log.error("删除移动备案记录异常：" + e.getMessage());
            return DataResult.fail("删除失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "更新移动备案记录")
    @PostMapping("/update")
    public DataResult update(@RequestBody MobileRecordEntity entity) {
        try {
            entity.setUpdateTime(new Date());
            mobileRecordService.updateById(entity);
            return DataResult.success();
        } catch (Exception e) {
            log.error("更新移动备案记录异常：" + e.getMessage());
            return DataResult.fail("更新失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "分页查询移动备案记录")
    @PostMapping("/listByPage")
    public DataResult listByPage(@RequestBody Map<String, Object> params) {
        try {
            Integer pageNum = ParamUtils.getInteger(params, "page");
            Integer pageSize = ParamUtils.getInteger(params, "limit");
            String companyName = ParamUtils.getString(params, "companyName");
            String appName = ParamUtils.getString(params, "appName");
            Integer status = ParamUtils.getInteger(params, "status");

            Page<MobileRecordEntity> page = new Page<>(pageNum, pageSize);
            QueryWrapper<MobileRecordEntity> wrapper = new QueryWrapper<>();

            if (companyName != null && !companyName.trim().isEmpty()) {
                wrapper.like("company_name", companyName);
            }
            if (appName != null && !appName.trim().isEmpty()) {
                wrapper.like("app_name", appName);
            }
            if (status != null) {
                wrapper.eq("status", status);
            }
            // 按创建时间倒序
            wrapper.orderByDesc("create_time");

            IPage<MobileRecordEntity> result = mobileRecordService.page(page, wrapper);
            return DataResult.success(result);
        } catch (Exception e) {
            log.error("查询移动备案记录异常：" + e.getMessage());
            return DataResult.fail("查询异常：" + e.getMessage());
        }
    }

    @ApiOperation(value = "获取移动备案记录详情")
    @GetMapping("/detail/{id}")
    public DataResult getDetail(@PathVariable Integer id) {
        try {
            // 明确指定只查询未删除的记录
            MobileRecordEntity entity = mobileRecordService.getOne(
                new QueryWrapper<MobileRecordEntity>()
                    .eq("id", id)
                    .eq("deleted", 0)
            );
            if (entity == null) {
                return DataResult.fail("记录不存在");
            }
            return DataResult.success(entity);
        } catch (Exception e) {
            log.error("获取移动备案记录详情异常：" + e.getMessage());
            return DataResult.fail("获取详情失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "设置为待提交状态")
    @PostMapping("/status/toPending/{id}")
    public DataResult toPending(@PathVariable Integer id) {
        try {
            MobileRecordEntity entity = new MobileRecordEntity();
            entity.setId(id);
            entity.setStatus(0);
            entity.setUpdateTime(new Date());
            mobileRecordService.updateById(entity);
            return DataResult.success();
        } catch (Exception e) {
            log.error("设置待提交状态异常：" + e.getMessage());
            return DataResult.fail("设置失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "设置为已提交状态")
    @PostMapping("/status/toSubmitted/{id}")
    public DataResult toSubmitted(@PathVariable Integer id) {
        try {
            MobileRecordEntity entity = new MobileRecordEntity();
            entity.setId(id);
            entity.setStatus(1);
            entity.setUpdateTime(new Date());
            mobileRecordService.updateById(entity);
            return DataResult.success();
        } catch (Exception e) {
            log.error("设置已提交状态异常：" + e.getMessage());
            return DataResult.fail("设置失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "设置为已备案状态")
    @PostMapping("/status/toFiled/{id}")
    public DataResult toFiled(@PathVariable Integer id) {
        try {
            MobileRecordEntity entity = new MobileRecordEntity();
            entity.setId(id);
            entity.setStatus(2);
            entity.setUpdateTime(new Date());
            mobileRecordService.updateById(entity);
            return DataResult.success();
        } catch (Exception e) {
            log.error("设置已备案状态异常：" + e.getMessage());
            return DataResult.fail("设置失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "批量更新状态")
    @PostMapping("/status/batchUpdateStatus")
    public DataResult batchUpdateStatus(@RequestBody Map<String, Object> params) {
        try {
            @SuppressWarnings("unchecked")
            List<Integer> ids = (List<Integer>) params.get("ids");
            Integer status = (Integer) params.get("status");

            if (ids == null || ids.isEmpty()) {
                return DataResult.fail("请选择要操作的记录");
            }

            for (Integer id : ids) {
                MobileRecordEntity entity = new MobileRecordEntity();
                entity.setId(id);
                entity.setStatus(status);
                entity.setUpdateTime(new Date());
                mobileRecordService.updateById(entity);
            }

            return DataResult.success();
        } catch (Exception e) {
            log.error("批量更新状态异常：" + e.getMessage());
            return DataResult.fail("批量更新失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "导入Excel数据")
    @PostMapping("/import")
    public DataResult importData(@RequestPart("file") MultipartFile file) {
        try {
            if (file == null || file.isEmpty()) {
                return DataResult.fail("请选择要导入的Excel文件");
            }

            String fileName = file.getOriginalFilename();
            if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
                return DataResult.fail("请选择Excel文件(.xlsx或.xls)");
            }

            Workbook workbook = new XSSFWorkbook(file.getInputStream());
            
            // 验证工作簿名称
            boolean foundTargetSheet = false;
            Sheet targetSheet = null;
            String targetSheetName = "移动";

            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                Sheet sheet = workbook.getSheetAt(i);
                String sheetName = sheet.getSheetName();
                if (sheetName != null && sheetName.equals(targetSheetName)) {
                    foundTargetSheet = true;
                    targetSheet = sheet;
                    break;
                }
            }
            
            if (!foundTargetSheet) {
                workbook.close();
                return DataResult.fail("未找到" + targetSheetName + "工作簿");
            }
            
            Sheet sheet = targetSheet;

            int successCount = 0;
            int failCount = 0;
            StringBuilder errorMsg = new StringBuilder();

            // 从第二行开始读取数据（第一行是标题）
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                try {
                    MobileRecordEntity record = new MobileRecordEntity();
                    
                    // 读取Excel数据并设置到实体对象
                    record.setCompanyName(getCellValue(row.getCell(0)));
                    record.setBureauDataPort(getCellValue(row.getCell(1)));
                    record.setCodeUsageRange(getCellValue(row.getCell(2)));
                    record.setAccessProvince(getCellValue(row.getCell(3)));
                    record.setAccessCity(getCellValue(row.getCell(4)));
                    record.setRealSendPort(getCellValue(row.getCell(5)));
                    record.setRealSendPortCompany(getCellValue(row.getCell(6)));
                    record.setRealSendPortCompanyCertType(getCellValue(row.getCell(7)));
                    record.setRealSendPortCompanyCertNumber(getCellValue(row.getCell(8)));
                    record.setLegalPersonName(getCellValue(row.getCell(9)));
                    record.setEnterpriseSignature(getCellValue(row.getCell(10)));
                    record.setAppName(getCellValue(row.getCell(11)));
                    record.setResponsiblePersonName(getCellValue(row.getCell(12)));
                    record.setResponsiblePersonCertType(getCellValue(row.getCell(13)));
                    record.setResponsiblePersonCertNumber(getCellValue(row.getCell(14)));
                    record.setAgentName(getCellValue(row.getCell(15)));
                    record.setAgentCertName(getCellValue(row.getCell(16)));
                    record.setAgentCertNumber(getCellValue(row.getCell(17)));
                    
                    // 处理日期字段
                    String authStartTimeStr = getCellValue(row.getCell(18));
                    if (authStartTimeStr != null && !authStartTimeStr.trim().isEmpty()) {
                        try {
                            // 尝试解析日期字符串
                            Date authStartTime = parseDateString(authStartTimeStr);
                            record.setAuthStartTime(authStartTime);
                        } catch (Exception e) {
                            log.warn("解析授权开始时间失败: " + authStartTimeStr + ", 错误: " + e.getMessage());
                            // 如果解析失败，设置为null
                            record.setAuthStartTime(null);
                        }
                    }
                    
                    String authEndTimeStr = getCellValue(row.getCell(19));
                    if (authEndTimeStr != null && !authEndTimeStr.trim().isEmpty()) {
                        try {
                            // 尝试解析日期字符串
                            Date authEndTime = parseDateString(authEndTimeStr);
                            record.setAuthEndTime(authEndTime);
                        } catch (Exception e) {
                            log.warn("解析授权结束时间失败: " + authEndTimeStr + ", 错误: " + e.getMessage());
                            // 如果解析失败，设置为null
                            record.setAuthEndTime(null);
                        }
                    }
                    
                    record.setSmsPortServiceType(getCellValue(row.getCell(20)));
                    record.setAdMarketingSmsCategory(getCellValue(row.getCell(21)));
                    record.setNeedSelfExtend(getCellValue(row.getCell(22)));
                    record.setFreeEnterpriseSignature(getCellValue(row.getCell(23)));
                    record.setSmsPortPurpose(getCellValue(row.getCell(24)));
                    record.setCarrierRoomLocation(getCellValue(row.getCell(25)));
                    record.setSmsPortEnterpriseRoomLocation(getCellValue(row.getCell(26)));
                    record.setContentTemplateExample(getCellValue(row.getCell(27)));
                    record.setContractAgreementText(getCellValue(row.getCell(28)));
                    record.setCustomerType(getCellValue(row.getCell(29)));
                    record.setAgentPhone(getCellValue(row.getCell(30)));
                    record.setResponsiblePersonPhone(getCellValue(row.getCell(31)));
                    record.setSignatureVerifyType(getCellValue(row.getCell(32)));
                    record.setBelongingCustomer(getCellValue(row.getCell(33)));

                    // 设置默认值
                    //record.setStatus(0);
                    record.setCreateTime(new Date());
                    record.setUpdateTime(new Date());

                    // 根据真实发送端口号进行upsert操作
                    QueryWrapper<MobileRecordEntity> wrapper = new QueryWrapper<>();
                    wrapper.eq("real_send_port", record.getRealSendPort());
                    wrapper.eq("deleted", 0);

                    MobileRecordEntity existingRecord = mobileRecordService.getOne(wrapper);
                    if (existingRecord != null) {
                        // 更新现有记录
                        record.setId(existingRecord.getId());
                        mobileRecordService.updateById(record);
                    } else {
                        // 新增记录
                        mobileRecordService.save(record);
                    }

                    successCount++;
                } catch (Exception e) {
                    failCount++;
                    errorMsg.append("第").append(i + 1).append("行数据导入失败：").append(e.getMessage()).append("; ");
                }
            }

            workbook.close();

            String resultMsg = String.format("导入完成：成功%d条，失败%d条", successCount, failCount);
            if (failCount > 0) {
                resultMsg += "。失败原因：" + errorMsg.toString();
            }

            return DataResult.success(resultMsg);
        } catch (IOException e) {
            log.error("导入Excel文件异常：" + e.getMessage());
            return DataResult.fail("导入失败：" + e.getMessage());
        } catch (Exception e) {
            log.error("导入数据异常：" + e.getMessage());
            return DataResult.fail("导入失败：" + e.getMessage());
        }
    }

    /**
     * 获取单元格值
     */
    private String getCellValue(Cell cell) {
        if (cell == null) {
            return null;
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    // 处理日期格式，转换为yyyy-MM-dd格式
                    Date date = cell.getDateCellValue();
                    return DateUtils.format(date, "yyyy-MM-dd");
                } else {
                    // 处理数字，避免科学计数法
                    double numericValue = cell.getNumericCellValue();
                    if (numericValue == (long) numericValue) {
                        return String.valueOf((long) numericValue);
                    } else {
                        return String.valueOf(numericValue);
                    }
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                try {
                    // 尝试获取公式计算结果
                    if (DateUtil.isCellDateFormatted(cell)) {
                        Date date = cell.getDateCellValue();
                        return DateUtils.format(date, "yyyy-MM-dd");
                    } else {
                        return String.valueOf(cell.getNumericCellValue());
                    }
                } catch (Exception e) {
                    return cell.getCellFormula();
                }
            default:
                return null;
        }
    }

    /**
     * 解析Excel日期字符串为Date对象
     */
    private Date parseDateString(String dateStr) {
        if (dateStr == null || dateStr.trim().isEmpty()) {
            return null;
        }
        
        dateStr = dateStr.trim();
        
        // 定义常见的日期格式
        String[] patterns = {
            "yyyy-MM-dd",
            "yyyy/MM/dd", 
            "yyyy/M/d",
            "yyyy-MM-dd HH:mm:ss",
            "yyyy/MM/dd HH:mm:ss",
            "yyyy/M/d HH:mm:ss"
        };
        
        for (String pattern : patterns) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                sdf.setLenient(false); // 严格模式
                return sdf.parse(dateStr);
            } catch (Exception e) {
                // 继续尝试下一个格式
                continue;
            }
        }
        
        // 如果所有格式都失败，尝试解析时间戳
        try {
            long timestamp = Long.parseLong(dateStr);
            return new Date(timestamp);
        } catch (Exception e) {
            log.warn("无法解析日期字符串: " + dateStr);
            return null;
        }
    }
}
